<template>
  <div class="settings">
    <el-card>
      <template #header>
        <span>安全设置</span>
      </template>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="修改密码" name="password">
          <el-form
            ref="passwordFormRef"
            :model="passwordForm"
            :rules="passwordRules"
            label-width="100px"
            style="max-width: 400px;"
          >
            <el-form-item label="原密码" prop="oldPassword">
              <el-input
                v-model="passwordForm.oldPassword"
                type="password"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="新密码" prop="newPassword">
              <el-input
                v-model="passwordForm.newPassword"
                type="password"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="passwordForm.confirmPassword"
                type="password"
                show-password
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updatePassword" :loading="loading">
                修改密码
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="个人信息" name="profile">
          <el-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-width="100px"
            style="max-width: 400px;"
          >
            <el-form-item label="姓名" prop="name">
              <el-input v-model="profileForm.name" />
            </el-form-item>
            
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="profileForm.sex">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>
            
            <el-form-item label="年龄" prop="age">
              <el-input-number 
                v-model="profileForm.age" 
                :min="1" 
                :max="100" 
                controls-position="right"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item label="星座" prop="constellation">
              <el-select v-model="profileForm.constellation" placeholder="请选择星座" style="width: 100%">
                <el-option
                  v-for="constellation in constellations"
                  :key="constellation"
                  :label="constellation"
                  :value="constellation"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="学校" prop="schoolId">
              <el-select v-model="profileForm.schoolId" placeholder="请选择学校" style="width: 100%">
                <el-option
                  v-for="school in schools"
                  :key="school.id"
                  :label="school.name"
                  :value="school.id"
                />
              </el-select>
            </el-form-item>
            
            <el-form-item label="专业" prop="major">
              <el-input v-model="profileForm.major" />
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="profileForm.email" />
            </el-form-item>
            
            <el-form-item label="自我介绍" prop="introduction">
              <el-input
                v-model="profileForm.introduction"
                type="textarea"
                :rows="3"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updateProfile" :loading="loading">
                更新信息
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../../stores/user'
import { ElMessage } from 'element-plus'
import api from '../../utils/api'

const userStore = useUserStore()
const activeTab = ref('password')
const loading = ref(false)
const schools = ref([])

const constellations = [
  '白羊座', '金牛座', '双子座', '巨蟹座', '狮子座', '处女座',
  '天秤座', '天蝎座', '射手座', '摩羯座', '水瓶座', '双鱼座'
]

const passwordFormRef = ref()
const profileFormRef = ref()

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const profileForm = reactive({
  name: '',
  email: '',
  major: '',
  introduction: '',
  sex: 0,
  age: '',
  constellation: '',
  schoolId: ''
})

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const profileRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '年龄必须在1-100之间', trigger: 'blur' }
  ],
  schoolId: [
    { required: true, message: '请选择学校', trigger: 'change' }
  ]
}

const updatePassword = async () => {
  if (!passwordFormRef.value) return
  
  await passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await api.put('/user/password', passwordForm)
        if (response.data.code === 200) {
          ElMessage.success('密码修改成功')
          passwordFormRef.value.resetFields()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('密码修改失败')
      } finally {
        loading.value = false
      }
    }
  })
}

const loadSchools = async () => {
  try {
    const response = await api.get('/auth/schools')
    if (response.data.code === 200) {
      schools.value = response.data.data
    }
  } catch (error) {
    console.error('加载学校列表失败:', error)
  }
}

const updateProfile = async () => {
  if (!profileFormRef.value) return
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await api.put('/user/info', profileForm)
        if (response.data.code === 200) {
          ElMessage.success('信息更新成功')
          userStore.getUserInfo()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('信息更新失败')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  // 初始化表单数据
  if (userStore.userInfo) {
    Object.assign(profileForm, {
      name: userStore.userInfo.name || '',
      email: userStore.userInfo.email || '',
      major: userStore.userInfo.major || '',
      introduction: userStore.userInfo.introduction || '',
      sex: userStore.userInfo.sex || 0,
      age: userStore.userInfo.age || '',
      constellation: userStore.userInfo.constellation || '',
      schoolId: userStore.userInfo.schoolId || ''
    })
  }
  loadSchools()
})
</script>

<style scoped>
.settings {
  padding: 20px;
}
</style>
